const { createApp, ref, computed, onMounted, onUnmounted } = Vue;

// Vue组件定义
const QueueComponent = {
    props: {
        index: {
            type: Number,
            required: true
        }
    },
    setup(props) {
        // 响应式数据
        const clientId = ref(generateRandomId());
        const socket = ref(null);
        const status = ref('idle'); // idle, waiting, active, selecting
        const message = ref('点击开始排队');
        const isConnected = ref(false);
        
        // 计算属性
        const statusText = computed(() => {
            switch (status.value) {
                case 'idle': return '空闲';
                case 'waiting': return '排队中';
                case 'active': return '可选号';
                case 'selecting': return '选号中';
                default: return '未知';
            }
        });
        
        const componentClass = computed(() => {
            return {
                'queue-component': true,
                'waiting': status.value === 'waiting',
                'active': status.value === 'active',
                'selecting': status.value === 'selecting'
            };
        });
        
        const showStartButton = computed(() => status.value === 'idle');
        const showSelectButton = computed(() => status.value === 'active');
        const showEndButton = computed(() => status.value === 'selecting');
        
        const displayClientId = computed(() => {
            return `组件 ${props.index} (ID: ${clientId.value.substr(-8)})`;
        });
        
        // 方法
        function generateRandomId() {
            return 'client_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
        }
        
        function connectWebSocket() {
            if (socket.value && socket.value.readyState === WebSocket.OPEN) {
                return;
            }
            
            socket.value = new WebSocket('ws://localhost:8080/queue');
            
            socket.value.onopen = () => {
                isConnected.value = true;
                console.log(`组件 ${props.index} WebSocket连接已建立`);
            };
            
            socket.value.onmessage = (event) => {
                const data = JSON.parse(event.data);
                handleMessage(data);
            };
            
            socket.value.onclose = () => {
                isConnected.value = false;
                console.log(`组件 ${props.index} WebSocket连接已关闭`);
            };
            
            socket.value.onerror = (error) => {
                console.error(`组件 ${props.index} WebSocket错误:`, error);
                message.value = '连接错误，请重试';
            };
        }
        
        function sendMessage(type) {
            if (socket.value && socket.value.readyState === WebSocket.OPEN) {
                const msg = {
                    type: type,
                    clientId: clientId.value
                };
                socket.value.send(JSON.stringify(msg));
            }
        }
        
        function handleMessage(data) {
            switch (data.type) {
                case 'CAN_START':
                    status.value = 'active';
                    message.value = data.message;
                    break;
                case 'WAITING':
                    status.value = 'waiting';
                    message.value = data.message;
                    break;
                case 'LEFT_QUEUE':
                    status.value = 'idle';
                    message.value = '已离开队列，点击开始排队';
                    break;
                case 'NOT_IN_QUEUE':
                    status.value = 'idle';
                    message.value = '点击开始排队';
                    break;
            }
        }
        
        function startQueue() {
            connectWebSocket();
            
            // 等待连接建立后发送消息
            const checkConnection = () => {
                if (socket.value && socket.value.readyState === WebSocket.OPEN) {
                    sendMessage('JOIN_QUEUE');
                } else {
                    setTimeout(checkConnection, 100);
                }
            };
            
            checkConnection();
        }
        
        function startSelecting() {
            status.value = 'selecting';
            message.value = '正在选号中...';
        }
        
        function endSelecting() {
            sendMessage('LEAVE_QUEUE');
            status.value = 'idle';
            message.value = '选号完成，点击开始排队';
            
            if (socket.value) {
                socket.value.close();
            }
        }
        
        // 生命周期
        onUnmounted(() => {
            if (socket.value) {
                socket.value.close();
            }
        });
        
        return {
            clientId,
            status,
            message,
            isConnected,
            statusText,
            componentClass,
            showStartButton,
            showSelectButton,
            showEndButton,
            displayClientId,
            startQueue,
            startSelecting,
            endSelecting
        };
    },
    template: `
        <div :class="componentClass">
            <div class="component-header">
                <span class="component-id">{{ displayClientId }}</span>
                <span :class="'status ' + status">{{ statusText }}</span>
            </div>
            <div class="message">{{ message }}</div>
            <div class="buttons">
                <button 
                    v-if="showStartButton"
                    class="btn-start" 
                    @click="startQueue"
                    :disabled="status !== 'idle'">
                    开始排队
                </button>
                <button 
                    v-if="showSelectButton"
                    class="btn-select" 
                    @click="startSelecting">
                    开始选号
                </button>
                <button 
                    v-if="showEndButton"
                    class="btn-end" 
                    @click="endSelecting">
                    结束选号
                </button>
            </div>
            <div :class="'connection-status ' + (isConnected ? 'connected' : 'disconnected')">
                {{ isConnected ? '已连接' : '未连接' }}
            </div>
        </div>
    `
};

// 创建Vue应用
createApp({
    components: {
        QueueComponent
    }
}).mount('#app');